/**
 * 
 */
package com.feib.stms.batch.dao.rowmapper;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.support.JdbcUtils;

/**
 * @author Jimmy Liu
 *
 */
public class BaseRowMapper<T> extends BeanPropertyRowMapper<T> implements Serializable
{
	private static final long serialVersionUID = 4160256238926010073L;
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
    
	public BaseRowMapper(Class<T> mappedClass)
	{
		super(mappedClass);
	}
	
	
	protected Boolean getColumnBoolean(ResultSet rs, String columnName)
	{
		int index = 0;
		try {
			index = rs.findColumn(columnName);
		} catch (SQLException e) {
			logger.warn("資料集(ResultSet)中資料欄名稱 ["+columnName+"] 無效，請先確認SQL Statement 有Select 此欄位.", e);
		}
		
		try {
			if (index > 0)
			{
				int i = rs.getInt(index);
				
				if (rs.wasNull()) {
					return null;
				}
				
				return (i > 0 ? Boolean.TRUE : Boolean.FALSE);
			}
				
		} catch (SQLException e) {
			logger.warn("資料集(ResultSet)中資料欄名稱 ["+columnName+"] 欄位值錯誤)", e);
		}
		
		return null;
	}
	
	protected Object getColumnValue(ResultSet rs, String columnName, Class requiredType)
	{
		int index = 0;
		try {
			index = rs.findColumn(columnName);
		} catch (SQLException e) {
			logger.trace("資料集(ResultSet)中資料欄名稱 ["+columnName+"] 無效，請先確認SQL Statement 有Select 此欄位.", e);
		}
		

		try {
			if (index > 0)
				return JdbcUtils.getResultSetValue(rs, index, requiredType);
		} catch (SQLException e) {
			logger.trace("資料集(ResultSet)中資料欄名稱 ["+columnName+"] 欄位值錯誤，可能型別轉型錯誤(需要轉為 " + requiredType + " 型態)", e);
		}
		
		return null;
	}
	
	@Override
	public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
		
		//先使用自動映射
		T object =  super.mapRow(rs, rowNumber);
		
		object = doOtherMapRow(rs, rowNumber, object);
		
		return object;
	}

	protected T doOtherMapRow(ResultSet rs, int rowNumber, T entity)
	{
		return entity;
	}
}
